<?php

namespace App\Http\Controllers\Admin\Customer;

use App\Http\Controllers\Admin\BaseAdminController;
use App\Models\UploadedFile;
use App\Models\Customers;
use App\Models\CustomersBind;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * 用户控制器
 *
 * @author lxp
 * @package App\Http\Controllers\User
 */
class CustomersController extends BaseAdminController
{

	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * 客服列表
	 *
	 * @author lxp 20170111
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function index()
	{
		// 处理排序
		$sort = request('sort', 'id');
		$order = request('order', 'desc');

		$query = Customers::orderBy($sort, $order);
		// 筛选用户名
		if (request('username')) {
			if (is_email(request('username'))) {
				$query->where('nickname', request('username'));
			} else {
				$query->where('username', 'LIKE', "%" . request('username') . "%");
			}
		}
		// 筛选注册时间
		if (request('created_at')) {
			list($begin, $end) = explode(' - ', request('created_at'));
			$query->whereBetween('created_at', [
				date('Y-m-d H:i:s', strtotime($begin)),
				date('Y-m-d H:i:s', strtotime('+1 day', strtotime($end)))
			]);
		}
		// 取得列表
		$customers = $query->select([
			'id',
			'qrcode',
			'wx',
			'username',
			'nickname',
			'created_at',
			'updated_at',
		])->paginate(parent::PERPAGE);
		// 将查询参数拼接到分页链接中
		$customers->appends(app('request')->all());

		return view('admin.customer.customers', [
			'goods' => $customers,
		]);
	}

	/**
	 * 添加用户
	 *
	 * @author lxp 20170825
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function add()
	{
		return view('admin.customer.customers_form');
	}

	/**
	 * 编辑用户
	 *
	 * @author lxp 20170111
	 * @param $uid
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function edit($uid)
	{
		// 取得用户信息
		$user = Customers::findOrFail($uid);

		return view('admin.customer.customers_form', [
			'user' => $user
		]);
	}

	/**
	 * 保存用户
	 *
	 * @author lxp 20170206
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function save()
	{
		// 保存用户信息
		DB::transaction(function () {
			$user = Customers::findOrNew(request('id'));
            $user->username = request('username');
			$user->nickname = request('nickname');
			$user->qrcode = request('qrcode');
			$user->wx = request('wx');
			$user->save();

			// 更新附件id
			if (!request('id')) {
				// 更新头像
				if (intval(request('qrcode_file_id'))) {
					UploadedFile::where('file_id', intval(request('qrcode_file_id')))->update(['item_id' => $user->id]);
				}
			}
		});

		return $this->success(get_session_url('index'));
	}

	/**
	 * 删除用户
	 *
	 * @author lxp 20160713
	 * @param int $uid
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function delete($uid)
	{
		if (request()->ajax() && intval($uid)) {
			// 删除用户
			Customers::destroy($uid);
			return $this->success();
		}
	}
}